package com.ibuonline.b2b.admin.action;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.dimeng.common.base.BaseAction;
import com.dimeng.common.util.EncryptUtil;
import com.dimeng.common.util.StringUtil;
import com.ibuonline.b2b.common.ServiceFactory;
import com.ibuonline.b2b.common.SpyMemcached;
import com.ibuonline.b2b.entity.SysUser;
import com.ibuonline.b2b.system.service.RoleService;
import com.ibuonline.b2b.system.service.SysUserService;

public class AdminLoginAction extends BaseAction{

	private static final long serialVersionUID = -1980731816829221189L;
	private static final Logger logger = Logger.getLogger(AdminLoginAction.class);
    private static Map<String, LinkedList<Long>> loginCountMap = new HashMap<String, LinkedList<Long>>();
	private SysUserService sysUserService = ServiceFactory.getSysUserService();
	private RoleService roleService = ServiceFactory.getRoleService();
    List<SysUser> sysUsers;
    private SysUser sysUser; 
	private String checkcode;
    private boolean needCaptcha;
    
    /**
	 * member login
	 * @return String of mapping view
	 */
	public String login() {
		if (sysUser == null || StringUtil.isEmpty(sysUser.getLoginName()) || 
							   StringUtil.isEmpty(sysUser.getPassword())) {
			setMessage(getText("auth.error.login.empty"));
			return INPUT;
		}

		long millis = System.currentTimeMillis();
		Timestamp now = new Timestamp(millis);
		SysUser sysUserObj = getSysUserByLoginName(sysUser.getLoginName());

		if (sysUserObj == null || (StringUtil.notEmpty(sysUserObj.getPassword()) && 
				!sysUserObj.getPassword().equals(EncryptUtil.md5(sysUser.getPassword())))) {
			setMessage(getText("auth.error.login.invalid"));
			if (sysUserObj != null) {
				LinkedList<Long> queue = loginCountMap.get(sysUser.getLoginName());
				if (queue == null) {
					queue = new LinkedList<Long>();
					loginCountMap.put(sysUserObj.getLoginName(), queue);
				}
				queue.offer(millis);
				if (queue.size() > 3)
					queue.poll();
				needCaptcha = queue.size() >= 3;
			}
			return INPUT;
		}

		if (needCaptcha) {
			String captcha = (String) getSession().getAttribute("KAPTCHA");
			//String captcha = (String)com.ibuonline.b2b.common.SpyMemcached.getInstance().asyncGet(getSession().getId()+":KAPTCHA");
			if (checkcode == null || !checkcode.equals(captcha))
				return INPUT;
		}

		loginCountMap.remove(sysUserObj.getLoginName());

		SpyMemcached.getInstance().set(ADMIN_ROLES + ":" + sysUserObj.getLoginName(), roleService.getSysRolesByUserId(sysUserObj.getUserId()));
		super.getSession().setAttribute(CURRENT_ADMIN, sysUserObj);
		super.getSession().setAttribute(USER_TYPE, ADMIN);
		super.addCookie("ln", EncryptUtil.base64Encode(sysUserObj.getLoginName()));
		logger.info(sysUserObj.getLoginName() + " login successful at " + now);
		return SUCCESS;
	}
	
	public String logout() {
		super.getSession().removeAttribute(CURRENT_ADMIN);
		super.getSession().removeAttribute(USER_TYPE);
		super.getSession().invalidate();
		super.removeCookie("ln");
		return SUCCESS;
	}
	
	private SysUser getSysUserByLoginName(String loginName) {
		sysUsers = sysUserService.getByParam("loginName", loginName);
		return (sysUsers.size() > 0) ? sysUsers.get(0) : null;
	}

	public List<SysUser> getSysUsers() {
		return sysUsers;
	}

	public void setSysUsers(List<SysUser> sysUsers) {
		this.sysUsers = sysUsers;
	}

	public SysUser getSysUser() {
		return sysUser;
	}

	public void setSysUser(SysUser sysUser) {
		this.sysUser = sysUser;
	}

	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	public String getCheckcode() {
		return checkcode;
	}

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	public boolean isNeedCaptcha() {
		return needCaptcha;
	}

	public void setNeedCaptcha(boolean needCaptcha) {
		this.needCaptcha = needCaptcha;
	}	
}
